﻿from platform.jutils import *

Xchar = 'X'
Ochar = 'O'
Fchar = '-'
N = 7

def createField():
	fld = [Fchar] * N * N
	_fldPset(fld, (0,   0), 		Xchar)
	_fldPset(fld, (N-1, 0),         Ochar)
	_fldPset(fld, (0, N-1),         Ochar)
	_fldPset(fld, (N-1, N-1),       Xchar)
	return fld

def canMakeTurn(fld, who):
	for x in range(N):
		for y in range(N):
			if (_fldP(fld, (x, y)) == who):
				if (_canMakeTurnP(fld, (x, y), who)):
					return true
	return false
                        
def isItTurn(fld, ps, pd, who):
	(xs, ys) = ps
	(xd, yd) = pd
	if (xs < 0 or xs >= N or ys < 0 or ys >= N):
		return false
	if (xd < 0 or xd >= N or yd < 0 or yd >= N):
		return false
	if (_fldP(fld, ps) != who or _fldP(fld, pd) != Fchar):
		return false
	if (xs == xd and ys == yd):
		return false
	if (abs(xs-xd)>2 or abs(ys-yd)>2):
		return false
	return true

def whoseWin(fld):
	if (fld.count(Fchar) > 0):
		return Fchar
	Xcount = fld.count(Xchar)
	Ocount = fld.count(Ochar)
	if (Xcount > Ocount):
		return Xchar
	return Ochar

def makeTurn(fld, ps, pd):
	(xs, ys) = ps
	(xd, yd) = pd
	s = _fldP(fld, ps)
	if (abs(xs-xd)==2 or abs(ys-yd)==2):
		_fldPset(fld, ps, Fchar)
	_fldPset(fld, pd, s)
	for dx in range(-1, 2):
		for dy in range(-1, 2):
			_neiboursTurn(fld, pd, dx, dy, s)

def _neiboursTurn(fld, pd, dx, dy, s):
	(x, y) = pd
	x += dx
	y += dy 
	
	if (dx == 0 and dy == 0):
		return
	if (x < 0 or x >= N or y < 0 or y >= N):
		return
	if (_fldP(fld, (x, y)) == Fchar):
		return
	
	_fldPset(fld, (x, y), s)

def _canMakeTurnP(fld, p, who):
	(x, y) = p
	for dx in range(-2, 3):
		for dy in range(-2, 3): 
			if (isItTurn(fld, p, (x+dx, y+dy), who)):
				return true
	return false
        
def _fldPset(fld, p, s):
	(x, y) = p
	fld[N*y + x] = s

def _fldP(fld, p):
	(x, y) = p
	return fld[N*y + x]
